<template>
  <div v-show="!isShowEdit">
    <el-row>
      <el-col :md="6" :sm="24" class="leftOrgTree">
        <el-card style="height: 100%">
          <cr-org-tree v-model="orgObj" :treeHeight="leftOrgTreeHeight"></cr-org-tree>
          <!-- <orgTree v-model="orgObj" :treeHeight="leftOrgTreeHeight"></orgTree> -->
        </el-card>
      </el-col>
      <el-col :md="18" :sm="24">
        <div class="table-page-search-wrapper">
          <!--搜索-->
          <el-card>
            <el-form inline :model="queryParams" @submit.native.prevent>
              <el-row :gutter="48">
                <!-- 搜索item项 -->
                <el-col :md="8" :sm="24">
                  <el-form-item label="姓名" prop="keyword">
                    <el-input v-model.trim="queryParams.name" placeholder="请输入姓名" clearable />
                  </el-form-item>
                </el-col>
                <el-col :md="8" :sm="24">
                  <el-form-item label="用户名" prop="keyword">
                    <el-input v-model.trim="queryParams.userName" placeholder="请输入用户名" clearable />
                  </el-form-item>
                </el-col>
                <el-col :md="(isAdvanced && 8) || 0" :sm="(isAdvanced && 24) || 0">
                  <el-form-item label="手机号" prop="mobile">
                    <el-input v-model.trim="queryParams.mobile" placeholder="请输入手机号" clearable />
                  </el-form-item>
                </el-col>
                <!-- 查询按钮 -->
                <el-col :md="(!isAdvanced && 8) || 24" :sm="24">
                  <el-form-item>
                    <span class="table-page-search-submitButtons">
                      <el-button type="primary" @click="handleSearch">查 询</el-button>
                      <el-button style="margin-left: 8px" @click="resetQuery">重 置</el-button>
                      <a @click="isAdvanced = !isAdvanced" style="margin-left: 8px; color: #1482f0">
                        {{ isAdvanced ? '收起' : '展开' }}
                        <i :class="isAdvanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />
                      </a>
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </div>

        <div class="table-block">
          <el-card>
            <div slot="header" class="clearfix">
              <!-- 左侧修改新增按钮组 -->
              <div class="left">
                <el-button type="primary" @click="handleAdd('add', null)" v-if="menuButtonPermissions.includes('userInfo.add')">新 增</el-button>
                <el-button type="primary" v-else style="visibility: hidden;">新 增</el-button>

              </div>
              <!-- 右侧按钮组 -->
              <div class="right">
                <div class="table-operator card-right"></div>
              </div>
            </div>
            <el-table
              :data="tableList"
              row-key="id"
              stripe
              :height="isAdvanced ? isAdvancedtableMaxHeigth : tableMaxHeigth"
            >
              <el-table-column type="index" label="序号" align="center" width="50" />
              <el-table-column prop="name" label="姓名" align="center" show-overflow-tooltip />
              <el-table-column prop="category" label="来源方式" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  {{ scope.row.category === 1 ? '内部' : scope.row.category === 2 ? '外部' : '未知' }}
                </template>
              </el-table-column>
              <el-table-column prop="userName" label="用户名" align="center" show-overflow-tooltip />
              <el-table-column prop="mobile" label="手机号" align="center" show-overflow-tooltip />
              <el-table-column prop="state" label="是否禁用" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  {{ scope.row.state === 1 ? '正常' : (scope.row.state === 2 ? '锁定' : '禁用') }}
                </template>
              </el-table-column>
              <el-table-column prop="state" label="用户同步状态" align="center" show-overflow-tooltip width="200" >
                <template slot-scope="scope">
                  <el-switch
                    class="switch"
                    :active-value="true"
                    :inactive-value="false"
                    v-model="scope.row.ifSync"
                    @change="ifSyncChange(scope.row)"
                    :disabled="!menuButtonPermissions.includes('userInfo.upd')"
                    active-text="同步"
                    inactive-text="不同步">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="orgName" label="机构名称" align="center" show-overflow-tooltip />
              <el-table-column prop="fullNames" label="全路径" align="center" show-overflow-tooltip />
              <el-table-column label="操作" align="center" width="100" v-if="menuButtonPermissions.includes('userInfo.upd') || menuButtonPermissions.includes('userInfo.delete')">
                <template #default="{ row }">
                  <el-button
                    type="text"
                    icon="el-icon-edit"
                    class="table-button-size"
                    title="编辑"
                    v-if="menuButtonPermissions.includes('userInfo.upd')"
                    @click="handleAdd('update', row)"
                  ></el-button>
                  <el-button
                    type="text"
                    icon="el-icon-delete"
                    class="table-button-size"
                    title="删除"
                    v-if="menuButtonPermissions.includes('userInfo.deleted')"
                    @click="handleDelete(row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              :total="total"
              :page.sync="queryParams.pageNo"
              :limit.sync="queryParams.pageSize"
              @pagination="getTableList"
            />
          </el-card>
        </div>
      </el-col>
    </el-row>
    <edit ref="editRef" @getTableList="getTableList" :tableList="tableList" :orgObj="orgObj"></edit>
  </div>
</template>

<script>
import { getUserList, userdelete, updSync } from '@/api/userManage'
import orgTree from './components/orgTree'
import edit from './components/edit.vue'
import actions from '@/cros/actions'

export default {
  name: 'UserManage',
  components: {
    orgTree,
    edit
  },
  data () {
    return {
      isAdvanced: false,
      leftOrgTreeHeight: document.body.offsetHeight - 80,
      tableMaxHeigth: document.body.offsetHeight - 500,
      isAdvancedtableMaxHeigth: document.body.offsetHeight - 500,
      orgObj: {},
      tableList: [],
      isShowEdit: false,
      isAuthorization: false,
      total: 0,
      // 查询参数
      queryParams: {
        pageNo: 1,
        name: '',
        userName: '',
        mobile: '',
        pageSize: 10,
        orgId: ''
      },
      menuButtonPermissions: [],
      rowData: {}
    }
  },
  watch: {
    orgObj: {
      handler: function (newVal) {
        console.log(newVal, 'newVal')
        if (!newVal?.id) return
        this.queryParams.orgId = newVal.id
        this.getTableList()
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    actions.onGlobalStateChange((state, prevState) => {
      this.menuButtonPermissions = state.menuButtonPermissions.map(v => v.buttonKey)
    }, true)
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.setTableHeight)
    // 初始化表格高度
    this.setTableHeight()
  },
  methods: {
      ifSyncChange (row) {
      updSync({ id: row.id, ifSync: row.ifSync }).then((res) => {
           if (res.code === 'success') {
            this.$message.success('操作成功')
           } else {
            row.state = !row.state
            this.$message.error(res.msg)
          }
         })
    },
    handleDelete (row) {
      this.$confirm(`是否删除名称为 '${row.name}' 的用户?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          userdelete({ id: row.id }).then((res) => {
            if (res.code === 'success') {
              this.$message.success('操作成功')
              this.getTableList()
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          console.log('取消删除')
        })
    },
    handleAdd (str, row) {
      this.$refs.editRef.open(str, JSON.parse(JSON.stringify(row)))
    },
    beforeDestroy () {
      // 组件销毁前移除事件监听
      window.removeEventListener('resize', this.setTableHeight)
    },
    setTableHeight () {
      this.$nextTick(() => {
        this.tableMaxHeigth = document.body.offsetHeight - 320
        this.isAdvancedtableMaxHeigth = document.body.offsetHeight - 362
      })
    },
    handleSearch () {
      this.queryParams.pageNo = 1
      this.getTableList()
    },
    // 获取列表数据
    async getTableList () {
      console.log(this.queryParams, 'this.queryParams')
      const res = await getUserList(this.queryParams)
      console.log('列表数据', res)
      this.tableList = res.data.list
      this.total = res.data.totalCount
    },
    // 重置
    resetQuery () {
      this.queryParams.name = ''
      this.queryParams.userName = ''
      this.queryParams.mobile = ''
      this.queryParams.pageNo = 1
      this.queryParams.pageSize = 10
      this.getTableList()
    }
  }
}
</script>

<style lang="scss" scoped>
.leftOrgTree {
  height: calc(100vh - 60px);
  padding: 10px;
  padding-right: 0;
}
</style>
